//
//  CHTimeUtils.swift
//  jyzx
//
//  Created by cyptt on 2022/5/10.
//

import UIKit

public class CHTimeUtils: NSObject {

    /**
     yyy-MM-dd 时间字符串转换成 date
     */
    public static func  stringToDate(_ dateString: String, format: String) -> Date? {
      let formatter = DateFormatter()
      formatter.dateFormat = format
      return formatter.date(from: dateString)
   }
    /**
      时间字符串yyyy-M-d 等转换成时间 yyy-MM-dd
     */
    public static  func  standardizeDateString(_ input: String) -> String? {
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "en_US_POSIX")
        
        // 尝试可能的输入格式
        let possibleFormats = [
            "yyyy-M-d",
            "yyyy-MM-d",
            "yyyy-M-dd"
        ]
        
        for format in possibleFormats {
            formatter.dateFormat = format
            if let date = formatter.date(from: input) {
                formatter.dateFormat = "yyyy-MM-dd"
                return formatter.string(from: date)
            }
        }
        
        return nil
    }
    /**
     时间格式转换成时间戳
     */
    public static func stringToTimestamp(_ timeString: String, format: String = "yyyy-MM-dd HH:mm:ss") -> Int? {
        let dfmatter = DateFormatter()
        dfmatter.dateFormat = format
        dfmatter.timeZone = TimeZone(identifier: "Asia/Shanghai") // 按需设置时区
        
        guard let date = dfmatter.date(from: timeString) else {
            print("时间格式解析失败")
            return nil
        }
        
        return Int(date.timeIntervalSince1970) // 返回秒级时间戳
    }
    /**
     是否在某页时间内，比如30天
     @param endTime 截止时间戳
    true 30 天内 == 30 false30天外
       
     */
    public static func isInTime(endTime:String?,compareDay:Int? = 30)->Bool{
        let count:Int =  (Int(endTime!) ?? 0) - (Int(CHTimeUtils.getCurrentimeStamp()) ?? 0)*1000
 
        let result = count/(60*1000*24*60)
        print(result)
        if result < compareDay!{
            
            return true
        }else{
            return false
        }
    }
    
    /*
     获取当前时间戳
     */
    public  static func getCurrentimeStamp()->String{
        let now = Date()
        
        let timeIntervarl:TimeInterval = now.timeIntervalSince1970
        let timestamp:Int = Int(timeIntervarl)
        print(timestamp)
        return String(timestamp)
    }
    /*
     date 转是时间格式字符串
     */
    public  static func dateToTimeString(timeDate:Date,format:String?) -> String{
        
        let formatter:DateFormatter = DateFormatter()
        formatter.timeZone = NSTimeZone.init(name: "beijin") as TimeZone?
        formatter.dateStyle = DateFormatter.Style.medium
        formatter.timeStyle = DateFormatter.Style.short
        
        formatter.locale = Locale(identifier: "zh_CN")
        formatter.calendar = Calendar(identifier: Calendar.Identifier.gregorian)
        if format == nil || format! == "" {
//            formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
            formatter.dateFormat = "yyyy-MM-dd"
        }else{
            formatter.dateFormat = format
        }
        
        let dateStr:String = formatter.string(from: timeDate )
        
        return dateStr
    }
    
    /*
     时间戳转时间字符串
     */
    public static func timeStampToTimeString(timeStamp:String,format:String?) -> String{
        let timeDouble = (Double(timeStamp) ?? 0)/1000
        let date:Date? = Date.init(timeIntervalSince1970:timeDouble)
        
        let resultDateStr:String = self.dateToTimeString(timeDate: date!, format: format)
        return resultDateStr
    }
    
    public  static func timeStampToTimeString(timeStamp:Int,format:String?) -> String{
        let timeDouble = timeStamp/1000
        let date:Date? = Date.init(timeIntervalSince1970:TimeInterval(timeDouble))
        
        let resultDateStr:String = self.dateToTimeString(timeDate: date!, format: format)
        return resultDateStr
    }
    
    /*
     date1 > date2 true
     */
    public static func compareDate(date1:Date,date2:Date) -> Bool{
        let result:ComparisonResult = date1.compare(date2)
        print(result)
        
        if result == ComparisonResult.orderedDescending{
            print("date2<=date1")
            return false
        }else{
            return true
        }
       
    }
    
    /*
     时间格式转成小时分秒
     */
    
    public static func transToHourMinSec(timeStamp: Int,format:String) -> String
     {
         
         var hoursName:String = ":"
         var minutesName:String = ":"
         var secondsName:String = ""

         let allTime: Int = timeStamp
         var hours = 0
         var minutes = 0
         var seconds = 0
         var hoursText = ""
         var minutesText = ""
         var secondsText = ""
         
         hours = allTime / 3600
         hoursText = hours > 9 ? "\(hours)" : "0\(hours)"
         
         minutes = allTime % 3600 / 60
         minutesText = minutes > 9 ? "\(minutes)" : "0\(minutes)"
         
         seconds = allTime % 3600 % 60
         secondsText = seconds > 9 ? "\(seconds)" : "0\(seconds)"
         
         if format.hasPrefix("HH")||format.hasPrefix("hh"){
             hoursName = format.sub(from: 2, to: 3)
             minutesName = format.sub(from: 5, to: 6)
             if format.count > 8{
                 secondsName = format.sub(from: 8, to: 9)
             }
          
             return "\(hoursText)\(hoursName)\(minutesText)\(minutesName)\(secondsText)\(secondsName)"
         } else if format.hasPrefix("MM")||format.hasPrefix("mm"){
             minutesName = format.sub(from: 2, to: 3)
             
             if format.count > 5{
                 secondsName = format.sub(from: 5, to: 6)
             }
         
             return "\(minutesText)\(minutesName)\(secondsText)\(secondsName)"
         }else{
             if format.count > 2{
                 secondsName = format.sub(from: 2, to: 3)
             }
          
             return "\(secondsText)\(secondsName)"
         }
    
     }
}
